<?php
namespace app\home\controller;
use app\common\controller\Table;
use think\Db;
use fileDeal\FileDeal;
use ui\Component;

Class TableModuleIndex extends Table{

    protected $table_header = [
        ['key'=>'id','name'=>'编码','search'=>0],
        ['key'=>'name','name'=>'模块命名','search'=>1],
        ['key'=>'module','name'=>'文件名','search'=>1],
        ['key'=>'icon','name'=>'图标','search'=>0],
        ['key'=>'sort','name'=>'排序','search'=>0],
        ['key'=>'is_hide','name'=>'是否隐藏','templet'=>"switchTpl(d,'is_hide')",'search'=>0],
        ['key'=>'create_time','name'=>'创建时间','search'=>0],
    ];
    public function data($page=1,$limit=10){
        parent::data($page,$limit);
        $res = $this->data;
        foreach ($res['data'] as $k=>$v){
            $dom = "<i class='{$v['icon']}'></i>";
            $res['data'][$k]['icon'] = $dom;
        }
        return json($res);//已经是结果 ajax
    }
    public function index(){
        parent::index();
        $table_pri =$this->privilege;
        $table_pri['read'] = 0;
        $this->assign([
            'table_header'=>$this->table_header,
            'pri'=>$table_pri
        ]);
        return $this->fetch();
    }
    public function recycleData($page=1,$limit=15){
        parent::recycleData($page,$limit);
        $res = $this->data;
        foreach ($res['data'] as $k=>$v){
            $dom = "<i class='{$v['icon']}'></i>";
            $res['data'][$k]['icon'] = $dom;
        }
        return json( $res );
    }
    public function recycleindex()
    {
        parent::recycleindex();
        $this->assign([
            'table_header'=> $this->table_header
        ]);
        return $this->fetch();
    }
    public function tableCreate($is_create = 0)
    {
        parent::tableCreate($is_create);
        $params = $this->actionData;
        Db::startTrans();
        try{
            $res1 = Db::name('top_nav')->where(['name'=>$params['name']])->find();
            $res2 = Db::name('top_nav')->where(['module'=>$params['module']])->find();
            if($res1||$res2){
               exit(encode(['code'=>0,'msg'=>'模块已存在！']));
            }
            $top_data = [
                'name'=>$params['name'],
                'module'=>$params['module'],
                'is_hide'=>$params['is_hide'],
                'icon'=>$params['icon'],
                'sort'=>$params['sort']
            ];
            $top_nav = Db::name('top_nav')->insert($top_data);
            $data = [
                'pid'=>0,
                'name'=>'桌面',
                'module'=>$params['module'],
                'controller'=>'home',
                'url'=> '/' . $params['module'] . '/home/index',
                'icon'=>'layui-icon layui-icon-home',
                'sort'=>9999
            ];
            $left_nav = Db::name('left_nav')->insert($data);
            if(!$top_nav||!$left_nav){
                throw new \Exception("添加失败！");
            }
            else{
                if($this->is_log){
                    $this->logIns('create',$params,1);
                    $this->table = 'left_nav';
                    $this->logIns('create',$data,1);
                }
            }

            if($this->system['File_create']){
                $file = new FileDeal();
                $ui = new Component();
                $module = lcfirst( $params['module'] );
                $Umodule = ucfirst( $params['module'] );
                if($module!='common'&&$module!='member'){
                    $moduleConfigText = $ui->moduleConfig();
                    $moduleControllerText = $ui->makeController(['name'=>$Umodule,'module'=>'admin']);
                    $C0 = $file->create('/application/admin/config/',$Umodule . '.php', $moduleConfigText);
                    $C1 = $file->create('/application/admin/controller/',$Umodule . '.php',$moduleControllerText);
                    $C2 = $file->create('/application/admin/view/'. $module,'index.html','');
                    $controllerText = $ui->makeController(['name'=>'Home','module'=>$module]);
                    $C3 = $file->create('/application/' . $module . '/controller/','Home.php',$controllerText);
                    $C4 = $file->create('/application/' . $module . '/view/home/','index.html','');
                    $layoutIndex = $ui->moduleLayout();
                    $C5 = $file->create('/application/' . $module . '/view/layout/','index.html',$layoutIndex);
                    $commonControllerText = $ui->makeController([
                        'name'=>'Common','module'=>$module,'is_index'=>0,
                        'use'=>['use app\common\controller\Admin;'],'extends'=>'Admin',
                        'action'=>['protected function _initialize(){
                                  parent::_initialize();
                                 }']
                    ]);
                    $C6 = $file->create('/application/' . $module . '/controller/','Common.php',$commonControllerText);
                }
                else{
                    throw new \Exception("添加失败！");
                }
            }
            Db::commit();
            exit(encode( ['code'=>1,'msg'=>'添加成功！','jump_url'=>true,'jump'=>'index'] ));
        }
        catch (\Exception $e) {
            Db::rollback();
            exit(encode( ['code'=>0,'msg'=>'添加失败！'] ));
        }
    }
    public function tableUpdate($is_update = 0)
    {
        parent::tableUpdate($is_update);
        $params = $this->actionData;
        $id = $params['id'];
        unset($params['id']);
        Db::startTrans();
        try{
            $res1 = Db::name('top_nav')->whereNotIn('id',$id)->where(['name'=>$params['name']])->find();
            $res2 = Db::name('top_nav')->whereNotIn('id',$id)->where(['module'=>$params['module']])->find();
            if($res1||$res2){
                exit(encode(['code'=>0,'msg'=>'模块已存在！']));
            }
            $updateData  = Db::name('top_nav')->where(['id'=>$id])->find();
            $top_data = [
                'name'=>$params['name'],
                'module'=>$params['module'],
                'is_hide'=>$params['is_hide'],
                'icon'=>$params['icon'],
                'sort'=>$params['sort']
            ];
            $top_nav = Db::name('top_nav')->where(['id'=>$id])->update($top_data);
            if(!$top_nav){
                throw new \Exception("修改失败！");
            }
            else{
                if($this->is_log){
                    $this->table = 'top_nav';
                    $this->logIns('update',$params,1);
                }
            }
            $left_nav = Db::name('left_nav')->where(['module'=>$updateData['module']])
            ->field(['create_time','update_time'],true)->select();
            foreach ($left_nav as $k=>$v){
                $left_nav[$k]['module'] = $params['module'];
                $url = $v['url'];
                if($url){
                    $url = str_replace($updateData['module'],$params['module'],$url);
                    $left_nav[$k]['url'] = $url;
                }
                $leftUpdate = Db::name('left_nav')->update($left_nav[$k]);
                if(!$leftUpdate){
                    throw new \Exception("修改失败！");
                }
                else{
                    if($this->is_log){
                        $this->table = 'left_nav';
                        $this->logIns('update',$left_nav[$k],1);
                    }
                }
            }
            //以下是文件生成//
            if($this->system['File_create']){
                $file = new FileDeal();
                $ui = new Component();
                //旧模块
                $readModule = lcfirst( $updateData['module'] );
                $readUmodule = ucfirst( $updateData['module'] );
                $module = lcfirst( $params['module'] );
                $Umodule = ucfirst( $params['module'] );

                if($readModule!='common'&&$readModule!='member'){
                    $U0 = $file->rename('/application/admin/config/'.$readUmodule .'.php',
                        '/application/admin/config/'.$Umodule .'.php');
                    if(!$U0['code']){
                        $moduleConfigText = $ui->moduleConfig();
                        $file->create('/application/admin/config/',$Umodule .'.php',$moduleConfigText);
                    }
                    $U1 = $file->rename('/application/admin/controller/' . $readUmodule . '.php',
                        '/application/admin/controller/'.$Umodule . '.php');
                    if(!$U1['code']){
                        $moduleControllerText = $ui->makeController(['name'=>$Umodule,'module'=>'admin']);
                        $file->create('/application/admin/controller/',$Umodule . '.php',
                            $moduleControllerText);
                    }
                    $U2 = $file->rename('/application/admin/view/' . $readModule
                        ,'/application/admin/view/' . $module)  ;
                    if(!$U2['code']){
                        $file->create('/application/admin/view/'. $module,'index.html','');
                    }
                    $U3 = $file->rename('/application/' . $readModule
                        ,'/application/'. $module);
                    if(!$U3['code']){
                        $controllerText = $ui->makeController(['name'=>'Home','module'=>$module]);
                        $file->create('/application/' . $module . '/controller/','Home.php',$controllerText);
                    }

                    //改变admin下的系统控制器名
                    $admincontroller = $file->read('/application/admin/controller/' . $Umodule . '.php');
                    if($admincontroller['code']){
                        $A1 =  str_replace(" " . $readUmodule . " "," " . $Umodule . " ",$admincontroller['data']);
                        $file->create('/application/admin/controller/' ,$Umodule . '.php',$A1);
                    }
                    //改变系统下的对应控制器
                    $controllerSelect = $file->select('/application/' . $module .'/controller/');
                    foreach ($controllerSelect as $k=>$v){
                        $controllerRead = $file->read('/application/' . $module .'/controller/' . $v);
                        if($controllerRead['code']){
                            $A2 = str_replace('namespace app\\'. $readModule .'\controller;',
                                'namespace app\\' . $module . '\controller;',$controllerRead['data']);
                            $file->create('/application/'.$module .'/controller/',$v,$A2);
                        }
                    }
                }
                else{
                    throw new \Exception("修改失败！");
                }
            }
            Db::commit();
            exit(encode( ['code'=>1,'msg'=>'修改成功！','jump_url'=>true,'jump'=>'index'] ));
        }
        catch (\Exception $e) {
            Db::rollback();
            exit(encode( ['code'=>0,'msg'=>'修改失败！'] ));
        }
    }
    public function delete($id = null)
    {
        $this->is_pri('delete');
        if(isset( $id )){
            $idArr = explode(',',$id);
            Db::startTrans();
            $params = [];$params['id'] = $id;
            try{
                $delete = Db::name('top_nav')->whereIn('id',$idArr)->update(['is_delete'=>1]);
                if(!$delete){
                    if($this->is_log){
                        $this->logIns('delete',$params,0);
                    }
                    throw new \Exception("删除失败！");
                }
                else{
                    if($this->is_log){
                        $this->logIns('delete',$params,1);
                    }
                    $top_data = Db::name('top_nav')->whereIn('id',$idArr)->select();
                    $module_arr = [];$id_arr=[];
                    foreach ($top_data as $k=>$v){
                        array_push($module_arr,$v['module']);
                        array_push($id_arr,$v['id']);
                    }
                    $left_select  = Db::name('left_nav')->whereIn('module',$module_arr)->select();
                    $left_id_arr = [];
                    foreach ($left_select as $k=>$v){
                        array_push($left_id_arr,$v['id']);
                    }
                    $left_del = Db::name('left_nav')->whereIn('module',$module_arr)->update(['is_delete'=>1]);
                    if(!$left_del){
                        if($this->is_log){
                            $this->table = 'left_nav';
                            $this->logIns('delete',['id'=>join(',',$left_id_arr)],0);
                        }
                        throw new \Exception("删除失败！");
                    }
                    else{
                        if($this->is_log){
                            $this->table = 'left_nav';
                            $this->logIns('delete',['id'=>join(',',$left_id_arr)],1);
                        }
                    }
                }
                Db::commit();
                exit(encode( ['code'=>1,'msg'=>'删除成功！','jump_url'=>true,'jump'=>'index'] ));
            }
            catch (\Exception $e) {
                Db::rollback();
                exit(encode( ['code'=>0,'msg'=>'删除失败！'] ));
            }
        }
        else{
            exit(encode( ['code'=>0,'msg'=>'缺少参数！'] ));
        }
    }
    //还原数据（回收站）
    public function reduction( $id = null ){
        $this->is_pri('delete');
        if(isset( $id )){
            $idArr = explode(',',$id);
            Db::startTrans();
            $params = [];$params['id'] = $id;
            try{
                $data = Db::name($this->table)->whereIn('id',$idArr)->update(['is_delete'=>0]);
                if($data){
                    if($this->is_log){
                        $this->logIns('reduction',$params,1);
                    }
                    $top_data = Db::name('top_nav')->whereIn('id',$idArr)->select();
                    $module_arr = [];$id_arr=[];
                    foreach ($top_data as $k=>$v){
                        array_push($module_arr,$v['module']);
                        array_push($id_arr,$v['id']);
                    }
                    $left_select  = Db::name('left_nav')->whereIn('module',$module_arr)->select();
                    $left_id_arr = [];
                    foreach ($left_select as $k=>$v){
                        array_push($left_id_arr,$v['id']);
                    }
                    $left_data = Db::name('left_nav')->whereIn('module',$module_arr)->update(['is_delete'=>0]);
                    if($left_data){
                        if($this->is_log){
                            $this->table = 'left_nav';
                            $this->logIns('reduction',['id'=>join(',',$left_id_arr)],1);
                        }
                    }
                    else{
                        if($this->is_log){
                            $this->table = 'left_nav';
                            $this->logIns('reduction',['id'=>join(',',$left_id_arr)],0);
                        }
                        throw new \Exception("还原失败！");
                    }
                }
                else{
                    if($this->is_log){
                        $this->logIns('reduction',$params,0);
                    }
                    throw new \Exception("还原失败！");
                }
                Db::commit();
                exit(encode( ['code'=>1,'msg'=>'还原成功！','jump_url'=>true,'jump'=>'recycleindex'] ));
            }
            catch (\Exception $e) {
                Db::rollback();
                exit( encode(['code'=>0,'msg'=>'还原失败！','data'=>[]]) );
            }
        }
        else{
           exit( encode( ['code'=>0,'msg'=>'缺少参数!','data'=>[]] ) );
        }
    }
    //删除回收站
    public function cleanUp( $id = null ){
        $this->is_pri('delete');
        $file = new FileDeal();
        $params = [];
        if(isset( $id )){
            Db::startTrans();
            if($id=='all'){
                $del = Db::name('top_nav')->where('is_delete',1)->select();
                $arr = [];$module_arr = [];
                foreach ($del as $v){
                    array_push($module_arr,$v['module']);
                    array_push($arr,$v['id']);
                }
                $id_log = implode(',',$arr);
                $params['id'] = $id_log;
                try{
                    $delete = Db::name('top_nav')->where('is_delete',1)->delete();
                    if(!$delete){
                        if($this->is_log){
                            $this->logIns('cleanUp',$params,0);
                        }
                        throw new \Exception("销毁失败！");
                    }
                    else{
                        if($this->is_log){
                            $this->logIns('cleanUp',$params,1);
                        }
                        $left_select  = Db::name('left_nav')->whereIn('module',$module_arr)->select();
                        $left_id_arr = [];
                        foreach ($left_select as $k=>$v){
                            array_push($left_id_arr,$v['id']);
                        }
                        $left_del = Db::name('left_nav')->whereIn('module',$module_arr)->delete();
                        if(!$left_del){
                            if($this->is_log){
                                $this->table = 'left_nav';
                                $this->logIns('cleanUp',['id'=>join(',',$left_id_arr)],0);
                            }
                            throw new \Exception("销毁失败！");
                        }
                        else{
                            if($this->is_log){
                                $this->table = 'left_nav';
                                $this->logIns('cleanUp',['id'=>join(',',$left_id_arr)],1);
                            }
                        }
                    }
                    //文件删除
                    foreach ($module_arr as $k=>$v){
                        $Umodule =  ucfirst($v);
                        $module = lcfirst($v);
                        $file->delete('/application/'. $module);
                        $file->delete('/application/admin/config/'. $Umodule . '.php');
                        $file->delete('/application/admin/controller/' . $Umodule . '.php');
                        $file->delete('/application/admin/view/' . $module);
                    }
                    Db::commit();
                    exit( encode(['code'=>1,'msg'=>'销毁成功！']) );
                }
                catch (\Exception $e) {
                    Db::rollback();
                    exit( encode(['code'=>0,'msg'=>'销毁失败！']) );
                }
            }
            else{
                $params['id'] = $id;
                $idArr = explode(',',$id);
                $top_data = Db::name('top_nav')->whereIn('id',$idArr)->select();
                $top_module = [];
                foreach ($top_data as $k=>$v){
                    array_push($top_module,$v['module']);
                }
                $delete = Db::name('top_nav')->where('is_delete',1)->
                whereIn('id',$idArr)->delete();
                try{
                    if(!$delete){
                        if($this->is_log){
                            $this->logIns('cleanUp',$params,0);
                        }
                        throw new \Exception("销毁失败！");
                    }
                    else{
                        if($this->is_log){
                            $this->logIns('cleanUp',$params,1);
                        }
                        $left_select  = Db::name('left_nav')->whereIn('module',$top_module)->select();
                        $left_id_arr = [];
                        foreach ($left_select as $k=>$v){
                            array_push($left_id_arr,$v['id']);
                        }
                        $left_delete = Db::name('left_nav')->whereIn('module',$top_module)->delete();
                        if(!$left_delete){
                            $this->table = 'left_nav';
                            if($this->is_log){
                                $this->logIns('cleanUp',['id'=>join(',',$left_id_arr)],0);
                            }
                            throw new \Exception("销毁失败！");
                        }
                        else{
                            if($this->is_log){
                                $this->logIns('cleanUp',['id'=>join(',',$left_id_arr)],1);
                            }
                        }
                    }

                    //文件部分删除
                    foreach ($top_module as $k=>$v){
                        $Umodule =  ucfirst($v);
                        $module = lcfirst($v);
                        $file->delete('/application/'. $module);
                        $file->delete('/application/admin/config/'. $Umodule . '.php');
                        $file->delete('/application/admin/controller/' . $Umodule . '.php');
                        $file->delete('/application/admin/view/' . $module);
                    }

                    Db::commit();
                    exit( encode(['code'=>1,'msg'=>'销毁成功！']) );
                }
                catch (\Exception $e) {
                    Db::rollback();
                    exit( encode(['code'=>0,'msg'=>'销毁失败！']) );
                }
            }

        }
        else{
          exit(  encode( ['code'=>0,'msg'=>'缺少参数!','data'=>[]] ) );
        }
    }

}